#include <iostream>
#include <vector>
#include <string>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 互斥锁
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;    // 条件变量

void *SlaverCore(void *arg)
{
    std::string name = static_cast<const char *>(arg);

    while (true)
    {
        // 加锁
        pthread_mutex_lock(&mutex);
        // 一般条件变量在加锁解锁间使用
        // mutex：释放前一半的锁，等待条件变量，等待结束后，重新加锁
        pthread_cond_wait(&cond, &mutex);

        std::cout << "SlaverCore " << name << " is working" << std::endl;

        // 解锁
        pthread_mutex_unlock(&mutex);
    }
}

void *MasterCore(void *arg)
{
    sleep(3);
    std::cout << "MasterCore is working" << std::endl;
    std::string name = static_cast<const char *>(arg);

    while (true)
    {
        pthread_cond_broadcast(&cond); // 唤醒所有等待的线程
        std::cout << "Master 唤醒一个线程" << std::endl;
        sleep(1);
    }
}

void StartMaster(std::vector<pthread_t> *tidsptr)
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, MasterCore, (void *)"Master Thread");
    if (n == 0)
    {
        std::cout << "MasterCore 线程创建成功" << std::endl;
    }
    tidsptr->emplace_back(tid);
}

void StartSlave(std::vector<pthread_t> *tidsptr, int thread_num = 3)
{
    for (int i = 0; i < thread_num; i++)
    {
        char *name = new char[64];
        snprintf(name, 64, "SlaveThread-%d", i + 1);
        pthread_t tid;
        int n = pthread_create(&tid, nullptr, SlaverCore, name);

        if (n == 0)
        {
            std::cout << "SlaveCore 线程创建成功" << std::endl;
            tidsptr->emplace_back(tid);
        }
    }
}

void WaitThread(std::vector<pthread_t> &tids)
{

    for (auto &tid : tids)
    {
        pthread_join(tid, nullptr);
    }
}


int main()
{
    std::vector<pthread_t> tids;
    StartMaster(&tids);
    StartSlave(&tids,5);

    WaitThread(tids);

    return 0;
}